package com.nut.lmsc.util;

import com.aliyun.ocr_api20210707.models.RecognizeIdcardResponseBody;
import com.fasterxml.jackson.databind.JsonNode;
import com.nut.lmsc.api.resp.PersonResp;
import com.nut.lmsc.common.Result;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Decoder;

import java.io.*;

@Data
@Slf4j
@Component
public class OcrAli {

    static final BASE64Decoder decoder = new BASE64Decoder();

    //阿里云 ACCESSKEYID
    @Value("${aliyun.accessKeyId}")
    private String accessKeyId;

    //阿里云 ACCESSKEYSECRET
    @Value("${aliyun.accessKeySecret}")
    private String accessKeySecret;

    public static final String ENDPOINT = "ocr-api.cn-hangzhou.aliyuncs.com";

    public static com.aliyun.ocr_api20210707.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 必填，您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = ENDPOINT;
        return new com.aliyun.ocr_api20210707.Client(config);
    }

    public Result<PersonResp> identOcr(String base64String) {

        byte[] bytes = null;
        try {
            bytes = decoder.decodeBuffer(base64String);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.fail();
        }
        ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
        return identOcr(inputStream);
    }

    public Result<PersonResp> identOcr(InputStream inputStream) {

        try {

            String path = "/opt/images/" + System.currentTimeMillis() + ".jpg";
//            String path = "D:\\" + System.currentTimeMillis() + ".jpg";
            File file = new File(path);

            log.info("write_img=" + path);
            FileOutputStream outputStream = new FileOutputStream(file);
            IoUtils.copy(inputStream, outputStream);

            FileInputStream inputStream2 = new FileInputStream(file);


            com.aliyun.ocr_api20210707.Client client = createClient(accessKeyId, accessKeySecret);
            com.aliyun.ocr_api20210707.models.RecognizeIdcardRequest request = new com.aliyun.ocr_api20210707.models.RecognizeIdcardRequest();

            request.setBody(inputStream2);

            com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();

            com.aliyun.ocr_api20210707.models.RecognizeIdcardResponse resp = client.recognizeIdcardWithOptions(request, runtime);

            RecognizeIdcardResponseBody body = resp.getBody();
            String data = body.getData();
            String code = body.getCode();

            if (StringTool.isNotEmpty(body.getMessage())) {
                return Result.fail(body.message);
            }

            JsonNode jsonNode = JacksonUtils.toObj(data);
            JsonNode person = jsonNode.get("data").get("face").get("data");
            String name = person.get("name").asText();
            String ident = person.get("idNumber").asText();

            PersonResp personResp = new PersonResp();
            personResp.setName(name);
            personResp.setIdent(ident);

            return Result.ok(personResp);
        } catch (Exception e) {
            log.info("identOcr_error", e);
        }
        return Result.fail();
    }


}
